package com.todod.base.module.base.service.apieisc;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import com.todod.base.module.base.controller.admin.apieisc.vo.*;
import com.todod.base.module.base.dal.dataobject.apieisc.ApiEiscDO;
import com.todod.base.framework.common.pojo.PageResult;
import com.todod.base.framework.common.pojo.PageParam;
import com.todod.base.framework.common.util.object.BeanUtils;

import com.todod.base.module.base.dal.mysql.apieisc.ApiEiscMapper;

import static com.todod.base.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.todod.base.module.base.enums.ErrorCodeConstants.*;

/**
 * EISC系统接口 Service 实现类
 *
 * @author 平台
 */
@Service
@Validated
public class ApiEiscServiceImpl implements ApiEiscService {

    @Resource
    private ApiEiscMapper apiEiscMapper;
    @Value("${eisc.domain-name}")
    private String domainName;
    @Value("${eisc.domain-username}")
    private String username;
    @Value("${eisc.domain-password}")
    private String password;
    @Value("${eisc.method.access-token}")
    private String accessToken;
    @Value("${eisc.method.well-list}")
    private String wellList;

    @Override
    public Long createApiEisc(ApiEiscSaveReqVO createReqVO) {
        // 插入
        ApiEiscDO apiEisc = BeanUtils.toBean(createReqVO, ApiEiscDO.class);
        apiEiscMapper.insert(apiEisc);
        // 返回
        return apiEisc.getId();
    }

    @Override
    public void updateApiEisc(ApiEiscSaveReqVO updateReqVO) {
        // 校验存在
        validateApiEiscExists(updateReqVO.getId());
        // 更新
        ApiEiscDO updateObj = BeanUtils.toBean(updateReqVO, ApiEiscDO.class);
        apiEiscMapper.updateById(updateObj);
    }

    @Override
    public void deleteApiEisc(Long id) {
        // 校验存在
        validateApiEiscExists(id);
        // 删除
        apiEiscMapper.deleteById(id);
    }

    private void validateApiEiscExists(Long id) {
        if (apiEiscMapper.selectById(id) == null) {
            throw exception(API_EISC_NOT_EXISTS);
        }
    }

    @Override
    public ApiEiscDO getApiEisc(Long id) {
        return apiEiscMapper.selectById(id);
    }

    @Override
    public PageResult<ApiEiscDO> getApiEiscPage(ApiEiscPageReqVO pageReqVO) {
        return apiEiscMapper.selectPage(pageReqVO);
    }

    @Override
    public String getEiscAccessToken() {
        String token = "", success = "", error = "";
        success = "getToken-----------------------------------调用成功";
        error = "getToken-----------------------------------调用失败";

        String url = domainName + accessToken;
        JSONObject requestMap = new JSONObject();
        requestMap.put("username", username);
        requestMap.put("password", password);

        String body = post(url, requestMap);
        String submitData = "";
        if (body != null && StringUtils.isNotBlank(body) && body.length() > 0) {
            JSONObject parseObject = JSON.parseObject(body);
            String code = parseObject.getString("code");
            String msg = parseObject.getString("msg");

            submitData = parseObject.getString("data");
            if (code == null || !code.equals("OK")) {
                System.out.println(error + "-----" + msg);
            } else {
                JSONObject parseObject1 = JSON.parseObject(submitData);
                token = parseObject1.getString("token");
                System.out.println(success);
            }
        }

        return token;
    }

    @Override
    public PageResult<EiscDataRespVO> getEiscWellList(String token, EiscPageReqVO pageReqVO) {
        String success = "", error = "";
        success = "getToken----------------------------------调用成功";
        error = "getToken----------------------------------调用失败";

        String url = domainName + wellList;

        String body = post(url, token);
        List<EiscDataRespVO> list = new ArrayList<>();
        if (body != null) {
            JSONObject parseObject = JSON.parseObject(body);
            String code = parseObject.getString("code");
            String data = parseObject.getString("data");
            if (code == null || !code.equals("OK")) {
                System.out.println(error);
            } else {
                JSONObject resultData = JSON.parseObject(data);
                String rows = resultData.getString("rows");

                JSONArray tableData = JSON.parseArray(rows);
                for (int i = 0; i < tableData.size(); i++) {
                    JSONObject jsonObject = tableData.getJSONObject(i);
                    EiscDataRespVO apiEiscDO = BeanUtils.toBean(jsonObject, EiscDataRespVO.class);

                    list.add(apiEiscDO);
                }
                System.out.println(success);
            }
        }

        IPage<EiscDataRespVO> page = new Page<>(pageReqVO.getPageNum(), pageReqVO.getPageSize());
        page.setRecords(list);
        page.setTotal(list.size());
        return new PageResult<>(page.getRecords(), page.getTotal());
    }

    public static String post(String url, JSONObject jsonPayload) {
        StringBuilder result = new StringBuilder();
        try {
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            // 添加请求头
            con.setRequestMethod("POST");
            con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            // 如果需要的话，可以添加Authorization请求头
            // con.setRequestProperty("Authorization", "Bearer " + token);

            // 发送POST请求必须设置如下两行
            con.setDoOutput(true);
            OutputStream os = con.getOutputStream();
            DataOutputStream wr = new DataOutputStream(os);

            // 发送JSON数据
            wr.writeBytes(jsonPayload.toString());
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();
            System.out.println("POST Response Code :: " + responseCode);

            if (responseCode == HttpURLConnection.HTTP_OK) { // success
                BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
                String inputLine;
                while ((inputLine = in.readLine()) != null) {
                    result.append(inputLine);
                }
                in.close();
            } else {
                System.out.println("POST request not worked.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public static String post(String url, String token) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
//            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
            conn.setRequestProperty("Authorization", token);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
//            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            return result;
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输出流、输入流
        finally {
            if (out != null) {
                out.close();
            }
        }
        return null;
    }

}